<template>
	<view class="content">
		<g-watermark/>
		<view class="content_form">
			<uni-segmented-control :current="current" :values="subsectionList" :style-type="'button'"
				:active-color="'#2979ff'" @clickItem="sectionChange"  />
			<u-form :model="formData" ref="form" :label-width="120" label-align="left">
				<u-form-item label="收件人" prop="userRealName" required v-if="current==0">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(0)">选择</text>
						<text @click="handleCS"
							style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送' }}</text>
						<!-- <text @click="handleMS"
							style="color:#0960bd;margin-left: 20rpx;">{{ isms ? '删除密送' : '添加密送' }}</text> -->
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers']"
								:key="item.key" @close="handleCloseTag(index,0)" closeable />
						</view>
					</view>
				</u-form-item>
				<u-form-item label="部门" prop="userRealName" required v-if="current==1">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleTkiTreeDepart()">选择</text>
						<text @click="handleCS"
							style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送' }}</text>
						<!-- <text @click="handleMS"
							style="color:#0960bd;margin-left: 20rpx;">{{ isms ? '删除密送' : '添加密送' }}</text> -->
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.name" mode="light" v-for="(item,index) in formData['hadDeptList']"
								:key="item.code" @close="handleCloseTag(index,3)" closeable />
						</view>
					</view>
				</u-form-item>
				<u-form-item label="抄送" v-if="iscs">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(1)">选择</text>
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers1']"
								:key="item.key" @close="handleCloseTag(index,1)" closeable />
						</view>
					</view>
				</u-form-item>
				<!-- <u-form-item label="密送" v-if="isms">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(2)">选择</text>
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers2']"
								:key="item.key" @close="handleCloseTag(index,2)" closeable />
						</view>
					</view>
				</u-form-item> -->
				<u-form-item label="主题" prop="title" required>
					<uni-easyinput v-model="formData.title" placeholder="请填写主题"></uni-easyinput>
				</u-form-item>
				<LEditor v-model="formData.content" ref="lEditorRef" />
				<u-form-item label="附件">
					<FileUpload ref="fileUploadRef"  :msgId="formData.id"/>
				</u-form-item>
				<template v-if="ishj">
					<u-form-item label="发送时间" prop="send_now" required>
						<u-radio-group v-model="formData.send_now" style="width: 100%;">
							<u-radio :name="'yes'" :wrap="true">
								立即发送
							</u-radio>
							<u-radio :name="'no'" :wrap="true">
								<view style="display: flex;gap:10rpx;align-items: center;">
									定时发送 <u-input disabled v-model="formData.send_time" placeholder="请选择时间" />
									<u-icon name="arrow-down" @click="showTime=true"></u-icon>
								</view>
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="回执" prop="receipt_state" required>
						<u-radio-group v-model="formData.receipt_state">
							<u-radio v-for="(item, index) in receipt_stateList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="等级" prop="msg_level" required>
						<u-radio-group v-model="formData.msg_level">
							<u-radio v-for="(item, index) in msg_levelList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</template>
			</u-form>
		</view>

		<view class="body_bottom">
			<template v-if="type == 'reply'">
				<view type="primary" @click="handleSend('reply')">确定</view>
				<view @click="handleResetWrite()">重写</view>
			</template>
			<template v-else>
				<view type="primary" @click="handleSend('send')">发送</view>
				<view @click="handleSend('draft')">保存草稿</view>
				<view @click="handleShowMore">高级功能</view>
			</template>
		</view>
		<MxDatepicker format="yyyy-mm-dd hh:ii" type="datetime" :show="showTime" :value="times" :show-tips="true"
			:show-seconds="false" @confirm="handleConfirmTime" @cancel="showTime=false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
		<TkiTree idKey="code" rangeKey="name" :range="departmentList" ref="tkiTreeDepartRef"
			@confirm="handleTkiTreeDepartConfirm" :multiple="true" />
	</view>
</template>

<script>
	import {
		postFormAction,
	} from '@/utils/request.js';
	import {
		msg_levelList,
		receipt_stateList,
	} from './writebox.js'
	import MxDatepicker from '../../component/mx-datepicker/mx-datepicker'
	import SelectUser from '@/components/selectUser/index.vue'
	import FileUpload from '../../component/file-upload/file-upload.vue'
	import LEditor from '../../component/l-editor/l-editor.vue'
	import TkiTree from '@/components/tki-tree/tki-tree.vue'
	import {
		mapState
	} from "vuex";
	export default {
		components: {
			MxDatepicker,
			SelectUser,
			FileUpload,
			LEditor,
			TkiTree
		},
		data() {
			const that = this
			return {
				msg_levelList,
				receipt_stateList,
				formData: {
					userRealName: "",
					userRealName1: "",
					userRealName2: "",
					title: "",
					content: "",
				},
				rules: {
					userRealName: [{
						required: true,
						message: `收件人不能为空`,
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					title: [{
						required: true,
						message: '主题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					// content: [{
					// 	required: true,
					// 	message: '正文不能为空',
					// 	// 可以单个或者同时写两个触发验证方式 
					// 	trigger: ['change', 'blur'],
					// }],
				},
				userType: 0, //1 是抄送 2是加密
				url: {
					sendMsg: '/message_oa/sendMsg',
					saveDraft: '/message_oa/saveDraft',
					reply: '/message_oa/reply'
				},
				currentRecord: {}, //当前数据
				ishj: false, //是否高级功能
				iscs: false, //抄送
				isms: false, //密送
				times: null,
				type: '',
				showTime: false,
				departmentList: [], //部门树
				subsectionList: ['发送到人员', '发送到部门'],
				current: 0,

			}
		},
		onLoad(options) {
			this.type = options.type || ''
			if (options.currentRecord) {
				this.currentRecord = JSON.parse(options.currentRecord)
			}
			this.getDepartmentsData()
			this.init()
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		computed: {
			...mapState(["emailType"]),
		},
		methods: {
			init() {
				this.$nextTick(() => {
					console.log("emailType", this.emailType)
					this.formData = {
						receiver: '',
						userRealName: "",
						userRealName1: "",
						receiver1: '',
						userRealName2: "",
						receiver2: '',
						title: "",
						content: "",
						send_now: 'yes',
						send_time: '',
						receiver: '',
						isToOutBox: 'true',
						receipt_state: 0,
						msg_level: 0,
					}
					this.formData.hadUsers = []
					this.formData.hadUsers1 = []
					this.formData.hadUsers2 = []
					this.formData.hadDeptList = []
					console.log("this.currentRecord", this.currentRecord)
					if (this.currentRecord && Object.keys(this.currentRecord).length) {
						this.formData.userRealName = this.currentRecord.receiverRealName;
						this.formData.receiver = this.currentRecord.receiver;
						this.formData.title = this.currentRecord.title;
						if (this.formData.receiver) {
							if (this.formData.receiver.indexOf('dept@') != -1) {
								this.current = 1
								this.formData.hadDeptList.push({
									code: this.formData.receiver.replaceAll('dept@', ''),
									name: this.formData.userRealName,
								});
							} else {
								this.current = 0
								this.formData.hadUsers.push({
									key: this.formData.receiver,
									name: this.formData.receiver,
									title: this.formData.userRealName,
									realName: this.formData.userRealName,
								});
							}
						}
					}

					this.$refs.form.resetFields()
				});
			},
			//高级功能
			handleShowMore() {
				this.ishj = !this.ishj;
			},
			handleCS() {
				this.iscs = !this.iscs;
				if (!this.iscs) {
					this.formData.userRealName1 = '';
					this.formData.receiver1 = '';
					this.formData.hadUsers1 = []
				}
			},
			handleMS() {
				this.isms = !this.isms;
				if (!this.isms) {
					this.formData.userRealName2 = '';
					this.formData.receiver2 = '';
					this.formData.hadUsers2 = []
				}
			},
			//部门时选择是否发送到部门
			sectionChange(e) {
				this.current = e.currentIndex;
				this.formData.userRealName = '';
				this.formData.receiver = '';
				this.formData.hadUsers = []
				this.formData.hadDeptList = []
				if (this.current == 0) {
					this.rules.userRealName[0].message = '收件人不能为空'
				} else if (this.current == 1) {
					this.rules.userRealName[0].message = '部门不能为空'
				}
				this.$refs.form.resetFields()
			},
			//选择人员
			handleSelectUser(type) {
				this.userType = type
				switch (this.userType) {
					case 0:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers']
						})
						break;
					case 1:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers1']
						})
						break;
					case 2:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers2']
						})
						break;
				}
			},
			//选择用户回调
			handleSelectUserConfirm({
				selectUserList,
				label,
				value
			}) {
				console.log("handleSelectUserConfirm", selectUserList)
				switch (this.userType) {
					case 0:
						this.formData.userRealName = label
						this.formData.receiver = value
						if (Array.isArray(this.formData['hadUsers'])) {
							this.formData['hadUsers'] = this.formData['hadUsers'].concat(selectUserList)
						} else {
							this.formData['hadUsers'] = selectUserList
						}
						this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
						this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
						break;
					case 1:
						this.formData.userRealName1 = label
						this.formData.receiver1 = value
						if (Array.isArray(this.formData['hadUsers1'])) {
							this.formData['hadUsers1'] = this.formData['hadUsers1'].concat(selectUserList)
						} else {
							this.formData['hadUsers1'] = selectUserList
						}
						this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
						this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
						break;
					case 2:
						this.formData.userRealName2 = label
						this.formData.receiver2 = value
						if (Array.isArray(this.formData['hadUsers2'])) {
							this.formData['hadUsers2'] = this.formData['hadUsers2'].concat(selectUserList)
						} else {
							this.formData['hadUsers2'] = selectUserList
						}
						this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
						this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
						break;
				}
				this.$forceUpdate()
			},
			//删除已选用户
			handleCloseTag(index, type) {
				switch (type) {
					case 0:
						this.formData['hadUsers'].splice(index, 1)
						this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
						this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
						break;
					case 1:
						this.formData['hadUsers1'].splice(index, 1)
						this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
						this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
						break;
					case 2:
						this.formData['hadUsers2'].splice(index, 1)
						this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
						this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
						break;
					case 3:
						this.formData['hadDeptList'].splice(index, 1)
						this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
						this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
						break;

				}
				this.$forceUpdate()
			},
			//回调时间
			handleConfirmTime(e) {
				console.log("handleConfirmTime", e)
				const {
					value
				} = e
				this.formData.send_time = value
				this.showTime = false
			},
			//选择部门
			handleTkiTreeDepart() {
				this.$refs.tkiTreeDepartRef._show()
			},
			//部门回调
			handleTkiTreeDepartConfirm(e) {
				let departmentSelected = []
				if (e && e.length) {
					departmentSelected = e
				}
				if (departmentSelected && departmentSelected.length) {
					const codes = this.formData['hadDeptList'].map(item => item.code)
					departmentSelected.forEach(item => {
						if (!codes.includes(item.code)) {
							this.formData['hadDeptList'].push(item)
						}
					})
				}
				this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
				this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
				this.$forceUpdate()

			},
			getDepartmentsData() {
				try {
					let params = {};
					postFormAction('/department/getDepartments', params).then((res) => {
						const {
							data
						} = res
						this.departmentList = data || [];
					});
				} catch (e) {
					console.error(e)
				} finally {}
			},
			handleReturn() {
				var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.isDoRefresh = true
				uni.navigateBack()
			},
			//重写
			handleResetWrite() {
				this.init()
			},
			//确定
			handleSend(type) {
				console.log("this.formData", this.formData)
				this.$refs.form.validate(async valid => {
					if (valid) {
						console.log('验证通过');
						try {
							this.formData.content = this.$refs.lEditorRef.content
							if (!this.formData.content) {
								uni.showToast({
									title: '请输入正文',
									icon: 'none'
								})
								return
							}
							const data = Object.assign({}, this.formData);
							delete data.hadUsers
							delete data.hadUsers1
							delete data.hadUsers2
							delete data.hadDeptList
							delete data.att
							if (this.current == 1) {
								data.isDept = true
							}
							const fileList = this.$refs.fileUploadRef.fileList
							console.log('fileList', fileList);
							// const files = []
							if (fileList && fileList.length) {
								data.attachments = fileList.map(item => item.id).join(',')
								// fileList.forEach((item, index) => {
								// files.push({
								// 	[`att${index + 1}`]: item,
								// 	name: 'file',
								// 	uri: item.tempFilePath
								// })
								// });
							}
							console.log('data', data);
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							let res = {}
							if (type == 'send') {
								res = await postFormAction(this.url.sendMsg, data);
							} else if (type == 'draft') {
								res = await postFormAction(this.url.saveDraft, data);
							} else if (type == 'reply') {
								res = await postFormAction(this.url.reply, data);
							}

							if (res.code == 200) {
								uni.showToast({
									title: '操作成功',
									icon: 'none'
								})
								this.handleReturn();
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						} catch (error) {
							console.log('handleSend', error);
						} finally {
							uni.hideLoading()
						}
					} else {
						console.log('验证失败');
					}
				});

			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		overflow-y: auto;

		&_form {
			padding: 20rpx 20rpx 0;
			margin-bottom: 800rpx;
		}
	}

	.body_bottom {
		position: fixed;
		z-index: 10;
		bottom: 0;
		height: 100rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		gap: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
	}
</style>